<?php

namespace app\admin\controller;

use app\admin\model\Account;
use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Collect extends Backend
{

    /**
     * Collect模型对象
     * @var \app\admin\model\Collect
     */
    protected $model = null;
    protected $dataLimit = 'auth';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Collect;

        $account = Account::where('status', 1)->field('id,email name,device_id')->select();
        foreach($account as $val){
            $val->mobile_serial = $val->device->mobile_serial ?? '';
            $val->name .= ' - '. $val->mobile_serial;
        }
        $this->view->assign('account', json_encode($account));
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            $filter = json_decode($this->request->get("filter", ''), true);
            $op = json_decode($this->request->get("op", '','trim'), true);
            $map = [];
            if (isset($filter['groupIds'])) {
                $groupIds = $this->auth->getByGroupIds($filter['groupIds']);
                $table_name = $this->model->getTable();
                $ids = model('AuthGroupAccess')->where('group_id', 'in', $groupIds)->column('uid');
                $map[$table_name . '.admin_id'] = ['in', $ids];
                unset($filter['groupIds'],$op['groupIds']);
            }
            $this->request->get(['filter' => json_encode($filter, true)]);
            $this->request->get(['op' =>json_encode($op, true)]);

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            // dd($where);
            $list = $this->model
                    ->where($map)
                    ->with(['admin','device','account'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            $last = $this->model->field('admin_id,account_id,device_id,date,fans')->select();
            $arr = [];
            foreach ($last as $row) {
                $arr[$row['account_id'] . $row['device_id'] . $row['date']] = $row['fans'];
            }
            // dd($arr);
            foreach ($list as $row) {
                
                $row->getRelation('admin')->visible(['nickname']);
				$row->getRelation('device')->visible(['name','mobile_serial','remark', 'ip', 'link_name']);
				$row->getRelation('account')->visible(['email','status', 'id', 'is_open']);
                if($row->device->link_name){
                    $row->link_url = $row->device->link . $row->device->link_name;
                }

                $row->account_status = $row->account->status;

                $row->yestoday_date = date('Y-m-d', strtotime($row->date) - 86400);
                $row->yestoday_fans = isset($arr[$row->account_id . $row->device_id . $row->yestoday_date]) 
                                ? $arr[$row->account_id . $row->device_id . $row->yestoday_date]
                                : 0;
                $row->fans_diff = abs($row->fans - $row->yestoday_fans);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $day = 6;
        $startdate = date('Y-m-d 00:00:00', strtotime("-$day day"));
        $enddate = date('Y-m-d 23:59:59');
        $this->assignconfig('date', $startdate . ' - '. $enddate);
        return $this->view->fetch();
    }

    /**
     * 查看
     */
    public function home()
    {
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            $filter = json_decode($this->request->get("filter", ''), true);
            $op = json_decode($this->request->get("op", '','trim'), true);
            $map = [];
            if(isset($filter['groupIds'])){
                $groupIds = $this->auth->getByGroupIds($filter['groupIds']);
                $table_name = $this->model->getTable();
                $ids = model('AuthGroupAccess')->where('group_id', 'in', $groupIds)->column('uid');
                $map[$table_name . '.admin_id'] = ['in', $ids];
                unset($filter['groupIds'],$op['groupIds']);
            }
            $this->request->get(['filter' => json_encode($filter, true)]);
            $this->request->get(['op' => json_encode($op, true)]);

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['admin','device','account'])
                    ->where($where)
                    ->where($map)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('admin')->visible(['nickname']);
				$row->getRelation('device')->visible(['name','mobile_serial','remark', 'ip', 'link', 'link_name', 'id']);
				$row->getRelation('account')->visible(['email','status', 'id']);
                if($row->device->link_name){
                    $row->link_url = $row->device->link . $row->device->link_name;
                }

                $row->account_status = $row->account->status;
            }
            
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $day = 6;
        $startdate = date('Y-m-d 00:00:00', strtotime("-$day day"));
        $enddate = date('Y-m-d 23:59:59');
        $this->assignconfig('date', $startdate . ' - '. $enddate);
        return $this->view->fetch();
    }

    /**
     * 查看
     */
    public function violent()
    {
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            $filter = json_decode($this->request->get("filter", ''), true);
            $op = json_decode($this->request->get("op", '','trim'), true);
            $map = [];
            if (isset($filter['groupIds'])) {
                $groupIds = $this->auth->getByGroupIds($filter['groupIds']);
                $table_name = $this->model->getTable();
                $ids = model('AuthGroupAccess')->where('group_id', 'in', $groupIds)->column('uid');
                $map[$table_name . '.admin_id'] = ['in', $ids];
                unset($filter['groupIds'],$op['groupIds']);
            }
            $this->request->get(['filter' => json_encode($filter, true)]);
            $this->request->get(['op' =>json_encode($op, true)]);

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            // dd($where);
            $list = $this->model
                    ->where($map)
                    ->with(['admin','device','account'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            $last = $this->model->field('admin_id,account_id,device_id,date,fans')->select();
            $arr = [];
            foreach ($last as $row) {
                $arr[$row['account_id'] . $row['device_id'] . $row['date']] = $row['fans'];
            }
            // dd($arr);
            foreach ($list as $row) {
                
                $row->getRelation('admin')->visible(['nickname']);
				$row->getRelation('device')->visible(['name','mobile_serial','remark', 'ip', 'link', 'link_name', 'id']);
				$row->getRelation('account')->visible(['email','status', 'id', 'is_open']);
                
                if($row->device->link_name){
                    $row->link_url = $row->device->link . $row->device->link_name;
                }
                $row->account_status = $row->account->status;

                $row->yestoday_date = date('Y-m-d', strtotime($row->date) - 86400);
                $row->yestoday_fans = isset($arr[$row->account_id . $row->device_id . $row->yestoday_date]) 
                                ? $arr[$row->account_id . $row->device_id . $row->yestoday_date]
                                : 0;
                $row->fans_diff = abs($row->fans - $row->yestoday_fans);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $day = 6;
        $startdate = date('Y-m-d 00:00:00', strtotime("-$day day"));
        $enddate = date('Y-m-d 23:59:59');
        $this->assignconfig('date', $startdate . ' - '. $enddate);
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add($account_id = null, $type = 1)
    {
        if (false === $this->request->isPost()) {
            
            $this->assign('type', $type);
            $this->assign('account_id', $account_id);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        $params['play_num'] = array_sum(explode('-', $params['play_num_str']));

        $device_id = Account::where('id',$params['account_id'])->value('device_id');
        $params['device_id'] = $device_id;

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
             $account = Account::where('status', 1)->field('id,email name,device_id')->select();
            foreach($account as $val){
                $val->mobile_serial = $val->device->mobile_serial ?? '';
                $val->name .= ' - '. $val->mobile_serial;
            }
            $this->view->assign('account', json_encode($account));
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $params['play_num'] = array_sum(explode('-', $params['play_num_str']));

        $device_id = Account::where('id',$params['account_id'])->value('device_id');
        $params['device_id'] = $device_id;

        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
}
